"""
Translation manager for PDF Splitter.
"""

import os
from typing import Optional
from PyQt6.QtCore import QObject, QTranslator, QLocale, QLibraryInfo, pyqtSignal
from PyQt6.QtWidgets import QApplication
from .languages import SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE, detect_system_language
from .simple_translations import translate as simple_translate


class Translator(QObject):
    """
    Manages application translations.
    """

    def __init__(self, parent: Optional[QObject] = None):
        super().__init__(parent)
        self._translators = {}
        self._current_language = DEFAULT_LANGUAGE
        self._app = QApplication.instance()
        self._use_simple_translator = True  # Use simple translator for now

        # Initialize with system language
        self.init_language()

    def init_language(self):
        """Initialize translation with detected system language."""
        detected_lang = detect_system_language()
        self.load_language(detected_lang)

    def load_language(self, language_code: str) -> bool:
        """
        Load a specific language.

        Args:
            language_code: Language code (e.g., 'en_US', 'zh_CN')

        Returns:
            True if language was loaded successfully
        """
        if language_code not in SUPPORTED_LANGUAGES:
            print(f"Warning: Language '{language_code}' is not supported")
            return False

        # Remove current translators
        self.unload_current_language()

        # Use simple translator - no need to load .qm files
        self._current_language = language_code
        return True

    def unload_current_language(self):
        """Unload all currently loaded translators."""
        if self._app:
            for translator in self._translators.values():
                self._app.removeTranslator(translator)
        self._translators.clear()

    def get_current_language(self) -> str:
        """Get current language code."""
        return self._current_language

    def set_language(self, language_code: str):
        """Set application language."""
        if self.load_language(language_code):
            # Emit language changed signal to update UI
            self.languageChanged.emit()

    # Signal to notify when language changes
    languageChanged = pyqtSignal()